package cn.lkp.mall.member.interceptor;

import cn.lkp.common.vo.MemberVo;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static cn.lkp.common.constant.AuthServerConstant.LOGIN_USER;


//将拦截器加入web配置后，就不用再加入容器了
//@Component
public class LoginUserInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberVo> loginUser = new ThreadLocal<>();
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        /**
         * 将"/member/**"路径放行
         */
        boolean match = antPathMatcher.match("/member/**", requestURI);
        if (match) {
            return true;
        }

        MemberVo attribute = (MemberVo) request.getSession().getAttribute(LOGIN_USER);
        if(attribute!=null){
            //把登录后用户的信息放在ThreadLocal里面进行保存
            loginUser.set(attribute);
            //放行以便执行目标方法
            return true;
        }else {
            //未登录，返回登录页面
            //TODO 在注册页加入msg
            request.getSession().setAttribute("msg","请先进行登陆");
            response.sendRedirect("http://auth.mall.com/login.html");
            return false;
        }
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
